package freedom.ms.auth.service.impl;

import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.ExampleMatcher.GenericPropertyMatchers;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import freedom.ms.auth.dao.MenuRepository;
import freedom.ms.auth.entity.Menu;
import freedom.ms.auth.service.MenuService;
@Service
public class MenuServiceImpl implements MenuService {
	@Autowired
	private MenuRepository menuRepository;

	@Override
	public Page<Menu> findAll(Pageable pageable) {
		return menuRepository.findAll(pageable);
	}
	
	@Override
	public Page<Menu> findAll(Menu menu, Pageable pageable) {
		ExampleMatcher matcher = ExampleMatcher.matching()
				.withMatcher(Menu.PROP_LEVEL, GenericPropertyMatchers.exact())
				.withMatcher(Menu.PROP_NAME, GenericPropertyMatchers.contains())
				.withIgnoreNullValues()
				;
		Example<Menu> e = Example.of(menu, matcher);
		return menuRepository.findAll(e , pageable);
	}
	
	@Override
	@Cacheable(value="menuCache", keyGenerator="keyGenerator")
	public List<Menu> findAll() {
		List<Menu> list = menuRepository.findAll();
		return list;
	}

	@Override
	@Cacheable(value="menuCache",key="#id")
	public Menu get(Long id) {
		Menu one = menuRepository.findOne(id);
		return one;
	}

	@Override
	@CachePut(value="menuCache",key="#menu.id")
	public Menu insert(Menu menu) {
		return menuRepository.save(menu);
	}

	@CachePut(value="menuCache",key="#menu.id")
	@Override
	public Menu update(Menu menu) {
		Menu old = this.get(menu.getId());
		BeanUtils.copyProperties(menu, old);
		return menuRepository.save(old);
	}
	
	@Override
	@CachePut(value="menuCache",key="#id")
	public void delete(Long id) {
		menuRepository.delete(id);
	}
	
	@Override
	@CacheEvict(value="menuCache",allEntries=true) // 清空缓存
	public List<Menu> reloadAll() {
		List<Menu> list = menuRepository.findAll();
		return list;
	}
	

}
